package deepseek.deepseekr1.service;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.json.JSONUtil;
import deepseek.deepseekr1.config.LocalAiConfig;
import deepseek.deepseekr1.config.RestTemplateConfig;
import deepseek.deepseekr1.entity.ChatRequest;
import deepseek.deepseekr1.entity.ChatResponse;
import deepseek.deepseekr1.entity.Message;
import deepseek.deepseekr1.entity.enums.MessageRoleEnum;
import deepseek.deepseekr1.utils.IpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class MessageService {

    private final RestTemplateConfig restTemplateConfig;

    private final LocalAiConfig localAiConfig;


    private final static Map<String, List<Message>> MESSAGE_MAP = new HashMap<>();


    public String askMessage(String message, HttpServletRequest request) {


//        final String clientIP = JakartaServletUtil.getClientIP(request);
        final String clientIP = IpUtils.getClientIp(request);

        log.info("start think:{},clientIp:{}", message, clientIP);


        String url = localAiConfig.getUrl() + "/api/chat";

        List<Message> userMessage = new ArrayList<>();

        if (MESSAGE_MAP.containsKey(clientIP)) {
            userMessage = MESSAGE_MAP.get(clientIP);
        }

        userMessage.add(Message.builder()
                .role(MessageRoleEnum.USER.getRole())
                .content(message)
                .build());

//        String requestBody = "{\"model\":\"deepseek-r1:32b\",\"options\":{},\"messages\":[{\"role\":\"user\",\"content\":\"通过 ollama 部署的 deepseek，可以看到请求对话是通过/api/chat 接口进行传输问题，但是如何拿到模型的回答？\",\"images\":[]}]}";

        final ChatRequest chatRequest = ChatRequest.builder()
                .model(localAiConfig.getModel())
                .messages(userMessage)
                .build();


        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        // 创建HttpEntity对象，它包含请求头和请求体
        HttpEntity<String> entity = new HttpEntity<>(JSONUtil.toJsonStr(chatRequest), headers);

        // 发送POST请求并获取响应
        String response = restTemplateConfig.restTemplate().postForObject(url, entity, String.class);

        final String[] split = response.split("\n");

        StringBuilder stringBuilder = new StringBuilder();

        for (String s : split) {
            final ChatResponse chatResponse = JSONUtil.parseObj(s).toBean(ChatResponse.class);

            if (!chatResponse.isDone()) {
                stringBuilder.append(chatResponse.getMessage().getContent());
            }
        }

        String answer = stringBuilder.toString();

        userMessage.add(Message.builder()
                .role(MessageRoleEnum.ASSISTANT.getRole())
                .content(answer)
                .build());

        MESSAGE_MAP.put(clientIP, userMessage);

        log.info("MESSAGE_MAP:{}", MESSAGE_MAP);

        return answer;
    }
}
